package com.bridgeintelligent.tag.engine.es.query.condition;

import com.bridgeintelligent.tag.engine.api.Filter;
import com.bridgeintelligent.tag.mapper.EsDateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @author JackCheung
 * @date 2020/4/16 7:40 PM.
 * description:
 */
@Component
public class DateBuilder {

    public static DateBuilder dateBuilder;

    @PostConstruct
    public void init() {
        dateBuilder = this;
    }

    @Autowired
    private EsDateMapper esDateMapper;

    private static final String ID_FORMAT = "%s_%s";

    public static final String ZERO = "0";

    public static final Integer LENGTH8 = 8;

    public static final Pattern pattern = Pattern.compile("[0-9]*");

    public static String handler(Filter filter) {

        //如果是动态
        if (!filter.isTimeType()){
            if (ZERO.equals(filter.getDataDate()) || (pattern.matcher(filter.getDataDate()).matches() && filter.getDataDate().length() == LENGTH8 )){
                return filter.getDimId();
            }else{
                String esSymbol = dateBuilder.esDateMapper.findEsSymbol(filter.getIndexId(), filter.getDataDate());
                esSymbol = Optional.ofNullable(esSymbol).orElse(filter.getDataDate());
                return String.format(ID_FORMAT, filter.getDimId(), esSymbol);
            }
        }else{
            return String.format(ID_FORMAT, filter.getDimId(), filter.getDataDate());
        }

    }

}
